package net.javamine.base;

import java.io.InputStreamReader;
import java.io.LineNumberReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Controller基类
 * @author <a href="mailto: java_lht@163.com">Lht</a>
 * @since 2012-11-23
 * @version 1.0
 */
public class BaseSpringMVCController {
	
	/**
	 * 获取客户端IP地址
	 * @param request HttpServletRequest
	 * @return ip
	 */
	public String getCilentIpAddress(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");  
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
			ip = request.getHeader("Proxy-Client-IP");  
		}  
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
			ip = request.getHeader("WL-Proxy-Client-IP");  
		}  
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
			ip = request.getRemoteAddr();  
		}  
		return ip;
	}
	
	/**
	 * 获取客户端MAC地址
	 * @param ip 客户端的IP地址
	 * @return mac
	 */
    public String getCilentMACAddress(String ip) throws Exception {
        String str = "";
        String macAddress = "";
        Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
        InputStreamReader ir = new InputStreamReader(p.getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        for (int i = 1; i < 100; i++) {
            str = input.readLine();
            if (str != null) {
                if (str.indexOf("MAC Address") > 1) {
                    macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
                    break;
                }
            }
        }
        return macAddress;
    }
	
	/**
	 * 将对象设置到Response中
	 * @param response HttpServletResponse
	 * @param obj 需要设置到response中的Object
	 * @throws Exception
	 */
	public void addObjectToResponse(HttpServletResponse response, Object obj) throws Exception {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(obj.toString());
	}

}
